import http from '@src/util/http';
import { getTimestampAtStartOfDay, getTimestampAtEndOfDay } from '@src/util/lang/index';
const prefix = '/api/workbench/outside';

/**
 * 查询视图列表
 * @param {String} module 模块
 */
export async function fetchViewportList(module) {
  try {
    const res = await http.get(`${prefix}/common/view/list`, { module });
    if (res.succ || res.status === 0) {
      // 视图中时间快捷选项今天、明天、后天时间处理
      const data = (res.data || []).map(item => {
        item.searchModel?.map(model => {
          if (model.operator == 'between') {
            if (model.timeType == 'today') {
              model.value[0] = getTimestampAtStartOfDay(0)
              model.value[1] = getTimestampAtEndOfDay(0)
            } else if (model.timeType == 'tomorrow') {
              model.value[0] = getTimestampAtStartOfDay(1)
              model.value[1] = getTimestampAtEndOfDay(1)
            } else if (model.timeType == 'dayAfterTomorrow') {
              model.value[0] = getTimestampAtStartOfDay(2)
              model.value[1] = getTimestampAtEndOfDay(2)
            }
          }
          return model
        })
        return item
      })
      return Promise.resolve(data);
    }
    return Promise.reject(res);
  } catch (error) {
    return Promise.reject(error);
  }
}

/**
 * 创建视图前的获取url
 * @param {String} params.module        视图模块
 */
 export async function getViewUrl(params) {
  try {
    const res = await http.get(`${prefix}/common/view/getViewUrl`, params);
    if (res.succ || res.status === 0) {
      return Promise.resolve(res.data);
    }
    return Promise.reject(res);
  } catch (error) {
    return Promise.reject(error);
  }
}

/**
 * 创建视图
 * @param {String} params.viewName      视图名称
 * @param {String} params.searchModel   视图搜索条件
 * @param {String} params.selectedCols  选择列
 * @param {Number} params.visibleType   视图类型 0个人 1全部
 * @param {String} params.module        视图模块
 */
export async function saveViewport(params) {
  try {
    const apiName = params.viewId ? 'update' : 'create'; // 区分新建、保存
    const res = await http.post(`${prefix}/common/view/${apiName}`, params);
    if (res.succ || res.status === 0) {
      return Promise.resolve(res.data);
    }
    return Promise.reject(res);
  } catch (error) {
    return Promise.reject(error);
  }
}

/**
 * 删除视图
 * @param {String} params.id      视图名称
 * @param {String} params.module        视图模块
 */
 export async function delViewport(params) {
  try {
    const res = await http.post(`${prefix}/common/view/delete`, params);
    if (res.succ || res.status === 0) {
      return Promise.resolve(res.data);
    }
    return Promise.reject(res);
  } catch (error) {
    return Promise.reject(error);
  }
}
